/*
 * Copyright (c) 2017 Jun Zhao
 * Copyright (c) 2017 Kaixuan Liu
 *
 * HW Acceleration API (video decoding) decode sample
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file
 * HW-Accelerated decoding example.
 *
 * @example hw_decode.c
 * This example shows how to do HW-accelerated decoding with output
 * frames from the HW video surfaces.
 */


#include <libavcodec/version.h>

#if LIBAVCODEC_VERSION_MAJOR >= 58

#include <libavcodec/avcodec.h>
#include <libavcodec/version.h>
#include <libavformat/avformat.h>
#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext.h>
#include <libavutil/opt.h>
#include <libavutil/avassert.h>
#include <libavutil/imgutils.h>
#include <stdio.h>
#include <error.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>

#include <sys/sysinfo.h>

#include "query_hw_codecInfo.h"
#include "device.h"
#include "utils.h"

#define DEFAULT_WRITE_FRAMES 20

static unsigned int g_hw_max_write_frames=DEFAULT_WRITE_FRAMES;
static unsigned long g_hw_decode_frames=0;

static int g_hw_dump_nv12 = 0;

static AVBufferRef *hw_device_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt;

static int g_hw_video_width = 0;
static int g_hw_video_height = 0;
static int g_hw_codecid = AV_CODEC_ID_NONE;

extern float get_cpu_usage(double time_period);
extern int g_vaapi_use_drm;


static int hw_decoder_init(AVCodecContext *ctx, const enum AVHWDeviceType type)
{
    int err = 0;
    // for ffmpeg 4.2 and newer version,options is neccesary
    //  otherwise drm will be used to initialize display
    // for ffmpeg 4.2 and older version,options is unused
    AVDictionary *options = NULL;
    av_dict_set(&options, "connection_type", g_vaapi_use_drm ? "drm" : "x11", 0);
    if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type,
                                      NULL, options, 0)) < 0)
    {
        fprintf(stderr,"Failed to create specified HW device.\n");
        fprintf(stderr, "Use '-d' option to select drm and take a try again.\n");
        return err;
    }
    ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
    return err;
}

static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
                                        const enum AVPixelFormat *pix_fmts)
{
    const enum AVPixelFormat *p;

    for (p = pix_fmts; *p != -1; p++)
    {
        // printf("cur pix format %d , dst pix fmt %d \n",*p,hw_pix_fmt);
        if (*p == hw_pix_fmt)
            return *p;
    }

    fprintf(stderr,"Failed to get HW surface format.\n");
    return AV_PIX_FMT_NONE;
}

static int decode_write(AVCodecContext *avctx, AVPacket *packet, const char *filedir,const char *short_name)
{
    AVFrame *frame = NULL, *sw_frame = NULL;
    AVFrame *tmp_frame = NULL;
    uint8_t *buffer = NULL;
    int ret = 0, size = 0;
    ret = avcodec_send_packet(avctx, packet);
    if (ret < 0)
    {
        fprintf(stderr,"Error during decoding\n");
        return ret;
    }

    while (1)
    {
        if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc()))
        {
            fprintf(stderr,"Can not alloc frame\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }

        ret = avcodec_receive_frame(avctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
        {
            av_frame_free(&frame);
            av_frame_free(&sw_frame);
            return 0;
        }
        else if (ret < 0)
        {
            fprintf(stderr,"Error while decoding\n");
            goto fail;
        }

        int decode_frames_num = avctx->frame_number;
        g_hw_decode_frames = decode_frames_num;
#if 1
        if (g_hw_dump_nv12 && decode_frames_num <= g_hw_max_write_frames)
        {
            if (frame->format == hw_pix_fmt)
            {
                /* retrieve data from GPU to CPU */
                if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0)
                {
                    fprintf(stderr,"Error transferring the data to system memory\n");
                    goto fail;
                }
                tmp_frame = sw_frame;
            }
            else
                tmp_frame = frame;

            size = av_image_get_buffer_size(tmp_frame->format, tmp_frame->width,
                                            tmp_frame->height, 1);
            buffer = av_malloc(size);
            if (!buffer)
            {
                fprintf(stderr,"Can not alloc buffer\n");
                ret = AVERROR(ENOMEM);
                goto fail;
            }
            ret = av_image_copy_to_buffer(buffer, size,
                                            (const uint8_t *const *)tmp_frame->data,
                                            (const int *)tmp_frame->linesize, tmp_frame->format,
                                            tmp_frame->width, tmp_frame->height, 1);
            if (ret < 0)
            {
                fprintf(stderr,"Can not copy image to buffer\n");
                goto fail;
            }
            char file_name[1024] = {0};
            snprintf(file_name, sizeof(file_name), "%s/%s-%d.nv12",filedir,short_name,decode_frames_num);
            FILE* fp = fopen(file_name, "w+");
            if (fp == NULL)
            {
              fprintf(stderr,"Failed to open file %s in decode_write",file_name);
              goto fail;
            }
            if ((ret = fwrite(buffer, 1, size, fp)) < 0)
            {
                fprintf(stderr,"Failed to dump raw data.\n");
                goto fail;
            }
            if(fp)fclose(fp);
        }
#endif
    fail:
        av_frame_free(&frame);
        av_frame_free(&sw_frame);
        if (buffer) av_freep(&buffer);
        if (ret < 0)
            return ret;
    }
    return 0;
}

typedef struct decoder {
    enum AVCodecID id;
    char*     decoder_name;
}decoder;

static decoder g_default_decoder[] = {
    {AV_CODEC_ID_H264, "h264"},
    {AV_CODEC_ID_HEVC, "hevc"},
    {AV_CODEC_ID_MPEG2VIDEO, "mpeg2video"},
};

int decoder_files(char* dec_type,char* filename, char* outdir,int dump_file_count)
{
    AVFormatContext *input_ctx = NULL;
    int vstream_idx=-1, ret = 0;
    AVStream *video = NULL;
    AVCodecContext *decoder_ctx = NULL;
    const AVCodec *decoder = NULL;
    AVPacket packet;
    enum AVHWDeviceType type;
    int i;

    printf("input hw decode tpye is %s\n", dec_type);

    char short_name[256] = {0};
    char *p;
    char *last_dot;


    strcpy(short_name, (p = strrchr(filename, '//')) ? p + 1 : filename);

    // printf("short_name1 is %s.\n", short_name);
    last_dot = strrchr(short_name, '.');
    if (last_dot != NULL)
        *last_dot = '\0';
        // printf("short_name2 is %s.\n", short_name);

    if (outdir && dump_file_count != 0)
    {
        g_hw_max_write_frames = dump_file_count;
        g_hw_dump_nv12 = 1;
        printf("using input write nv12 data numbers %d.\n", g_hw_max_write_frames);
    }

    type = av_hwdevice_find_type_by_name(dec_type);
    if (type == AV_HWDEVICE_TYPE_NONE)
    {
        fprintf(stderr,"Device type %s is not supported.\n", av_hwdevice_get_type_name(type));
        printf("Available device types:");
        while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
            printf(" %s", av_hwdevice_get_type_name(type));
        printf("\n");
        return -1;
    }

    /* open the input file */
    if (avformat_open_input(&input_ctx, filename, NULL, NULL) != 0)
    {
        fprintf(stderr,"Cannot open input file %s\n", filename);
        return -1;
    }

    if (avformat_find_stream_info(input_ctx, NULL) < 0)
    {
        fprintf(stderr,"Cannot find input stream information.\n");
        return -1;
    }

    /* find the video stream information */
    for (int i = 0; i < input_ctx->nb_streams; i++)
    {
	AVStream *st = input_ctx->streams[i];
	if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
	    continue;
	for (int j = 0; j < sizeof(g_default_decoder) / sizeof(g_default_decoder[0]); j++)
	{
	    if (g_default_decoder[j].id == st->codecpar->codec_id)
	    {
	        decoder = avcodec_find_decoder_by_name(g_default_decoder[j].decoder_name);
		break;
	    }
	}

	if (decoder != NULL)
	    break;

	if (av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0) < 0)
        {
            fprintf(stderr,"Cannot find a video stream in the input file\n");
            return -1;
        }
        break;
    }

    vstream_idx = ret;

    for (i = 0;; i++)
    {
        const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
        if (!config)
        {
            fprintf(stderr,"Decoder %s does not support device type %s.\n",
                    decoder->name, av_hwdevice_get_type_name(type));
            return -1;
        }
        if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
            config->device_type == type)
        {
            hw_pix_fmt = config->pix_fmt;
            break;
        }
    }

    if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
    {
        fprintf(stderr,"avcodec_alloc_context3 failed.\n");
        return -1;
    }

    video = input_ctx->streams[vstream_idx];
    if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0)
    {
        fprintf(stderr,"avcodec_parameters_to_context failed.\n");
        return -1;
    }

    g_hw_video_width = video->codecpar->width;
    g_hw_video_height = video->codecpar->height;
    g_hw_codecid = video->codecpar->codec_id;
    decoder_ctx->get_format = get_hw_format;

    if (hw_decoder_init(decoder_ctx, type) < 0)
    {
        fprintf(stderr,"Failed to init hardware decoder\n");
        return -1;
    }
    if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0)
    {
        fprintf(stderr,"Failed to open codec for stream %d\n", vstream_idx);
        return -1;
    }
#if 1
    struct timeval time_stamp;
    gettimeofday(&time_stamp, NULL);
    long packet_num = 0;
#define PACKET_INFO_PERIOD 100
    /* actual decoding and dump the raw data */
    while (ret >= 0)
    {
        if ((ret = av_read_frame(input_ctx, &packet)) < 0)
            break;

        if (vstream_idx == packet.stream_index)
        {
            ret = decode_write(decoder_ctx, &packet, outdir, short_name);
            if(ret)
            {
                fprintf(stderr,"decode_write failed\n");
            }
        }
        packet_num++;
        if (packet_num % PACKET_INFO_PERIOD == PACKET_INFO_PERIOD-1) {
          struct timeval time_point;
          gettimeofday(&time_point, NULL);
          long run_time =
              (time_point.tv_sec - time_stamp.tv_sec) * 1000 +
              (time_point.tv_usec - time_stamp.tv_usec) / 1000;
          printf("cpu   usage : %5.2f\n",get_cpu_usage(run_time / 1000.0));
          time_stamp = time_point;
        }
        av_packet_unref(&packet);
    }
    /* flush the decoder */
    packet.data = NULL;
    packet.size = 0;
    ret = decode_write(decoder_ctx, &packet, outdir , short_name);
    av_packet_unref(&packet);
#endif

    avcodec_free_context(&decoder_ctx);
    avformat_close_input(&input_ctx);
    av_buffer_unref(&hw_device_ctx);
    return 0;
}

long get_file_size(const char *filename)
{
    struct stat buf;
    stat(filename, &buf);
    return buf.st_size;
}

int hwdecode(astring dec_type, astring filename, astring outdir, int dump_image_count)
{
#if 1
    if (!strcmp("vaapi", dec_type)) {
      printf("\n***query vaapi support codecs begin***\n");
      if (query_vainfo() < 0) {
        fprintf(stderr,"\n***query vaapi support codecs error, quit***\n");
        return -1;
      }
      printf("\n***query vaapi support codecs end***\n");
    } else if (!strcmp("vdpau", dec_type)) {
      printf("\n***query vdpau support codecs begin***\n");
      if (query_vdpauinfo() < 0) {
        fprintf(stderr,"\n***query vdpau support codecs error, quit***\n");
        return -1;
      }
      printf("\n***query vdpau support codecs end***\n\n");
    } else {
      printf("\n***invalid hw decode tpye %s.***\n", dec_type);
      return -1;
    }
#endif
    struct timeval time_start, time_end;
    gettimeofday(&time_start, NULL);
    if (decoder_files(dec_type,filename,outdir,dump_image_count) < 0)
    {
        printf("\n***hw decode using %s failed.***\n", dec_type);
        return -1;
    }
    printf("*************print test result begin*************\n");

    gettimeofday(&time_end, NULL);
    double run_time = (time_end.tv_sec - time_start.tv_sec) * 1000 + (double)(time_end.tv_usec - time_start.tv_usec) / 1000;
    double runtime_second = run_time / 1000;
    double fps = g_hw_decode_frames / runtime_second;

    printf("hwdec decode           : %s\n", dec_type);
    printf("using totaltime        : %f sec\n", runtime_second);
    printf("codec                  : %s\n", avcodec_get_name(g_hw_codecid));
    printf("video size             : %d x %d\n", g_hw_video_width, g_hw_video_height);
    printf("decode frames          : %ld\n", g_hw_decode_frames);
    printf("decode fps             : %5.2f\n", fps);
    fprintf(stderr,"COUNT|%f|0|fps\n",fps);
    printf("*************print test result end*************\n");

    return 0;
}
#endif
